<template>
  <view class="home-page">
    <!-- 轮播图区域 -->
    <view class="banner-area">
      <swiper class="banner-swiper" circular autoplay interval="3000" duration="500">
        <swiper-item v-for="(item, index) in bannerList" :key="index">
          <image class="banner-img" :src="item.imageUrl" mode="aspectFill" />
        </swiper-item>
      </swiper>
    </view>

    <!-- 积分卡片，整体上移 -->
    <view class="score-card" @click="!isLoggedIn && openLoginModal()">
      <image class="avatar" src="https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/顾客默认头像.png" mode="aspectFill" />
      <view class="score-info">
        <view class="score-main">
          <view class="score-label">我的积分</view>
          <view class="score-value">{{ isLoggedIn ? userScore : '--' }}</view>
        </view>
        <view class="score-desc">可兑换优惠券及限量周边</view>
      </view>
      <view class="member-code">
        <image v-if="isLoggedIn" class="icon-code" src="https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/home-QRcode.jpg" mode="aspectFit" />
        <view class="code-label">会员码</view>
      </view>
    </view>

    <!-- 主要功能区 -->
    <view class="main-functions">
      <view class="func-row">
        <view class="func-item" @click="scanCode">
          <image class="func-icon" src="https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/home-house.png" mode="aspectFit" />
          <text class="func-title">扫码点餐</text>
        </view>
        <view class="func-item" @click="takeoutCode">
          <image class="func-icon takeout-icon" src="https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/home-motorcycle.jpg" mode="aspectFit" />
          <text class="func-title">外卖点单</text>
        </view>
      </view>
      <view class="func-row">
        <view class="func-item" @click="navigateTo('/src/pages/mine/service')">
          <image class="func-icon small-icon" src="https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/home-contact.jpg" mode="aspectFit" />
          <text class="func-title">联系客服</text>
        </view>
        <view class="func-item" @click="navigateTo('/src/pages/mine/recharge')">
          <image class="func-icon small-icon" src="https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/home-recharge.jpg" mode="aspectFit" />
          <text class="func-title">会员充值</text>
        </view>
        <view class="func-item" @click="navigateTo('/src/pages/mine/discount')">
          <image class="func-icon small-icon" src="https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/home-shop.jpg" mode="aspectFit" />
          <text class="func-title">积分商城</text>
        </view>
      </view>
    </view>

    <!-- 登录弹窗 -->
    <view class="login-modal" v-if="showLoginModal">
      <view class="login-content">
        <view class="login-header">
          <text class="login-title">登录</text>
          <text class="close-btn" @click="showLoginModal = false">×</text>
        </view>
        <view class="login-form">
          <input 
            class="login-input" 
            type="text" 
            v-model="loginForm.username" 
            placeholder="请输入手机号"
          />
          <input 
            class="login-input" 
            type="password" 
            v-model="loginForm.password" 
            placeholder="请输入密码"
          />
          <text class="forgot-password" @click="handleForgotPassword">忘记密码？</text>
          <button class="login-btn" @click="handleLogin">登录</button>
        </view>
      </view>
    </view>

  </view>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue'
import { userApi,boardApi } from '../../api/index'

// 轮播图数据
const bannerList = [
  {
    imageUrl: 'https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/home1.jpg'
  },
  {
    imageUrl: 'https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/home2.jpg'
  },
  {
    imageUrl: 'https://rsl-plus.oss-rg-china-mainland.aliyuncs.com/home3.jpg'
  }
]

// 用户登录状态
const isLoggedIn = ref(false)
// 用户信息
const userInfo = ref(null)
// 用户积分
const userScore = ref(0)

// 检查用户登录状态
const checkLoginStatus = () => {
  // TODO: 实际的登录状态检查逻辑
  const token = uni.getStorageSync('token');
  if (token) {
    // 假设 token 存在表示已登录
    isLoggedIn.value = true;
    // TODO: 可能需要验证 token 有效性，并获取用户信息
    fetchUserData(token);
  } else {
    isLoggedIn.value = false;
  }
};


// 获取用户积分
const fetchUserScore = async () => {
  try {
    const token = uni.getStorageSync('token')
    const res = await userApi.getUserScore(token)
    // 更新积分
    userScore.value = res.data.point || 0
  } catch (err) {
    console.error('获取用户积分失败：', err)
  }
}

// 在页面加载时检查登录状态
onMounted(() => {
  // 先检查登录状态
  if (checkLogin()) {
    // 已登录，获取数据
    //fetchUserData()
    fetchUserScore()  // 获取积分
  }
})

// 登录相关
const showLoginModal = ref(false)
const loginForm = ref({
  username: '',
  password: ''
})

// 检查登录状态
const checkLogin = () => {
  const token = uni.getStorageSync('token')
  if (!token) {
    showLoginModal.value = true
    isLoggedIn.value = false  // 未登录
    return false
  }
  isLoggedIn.value = true  // 已登录
  return true
}

// 处理忘记密码
function handleForgotPassword() {
  uni.showToast({
    title: '请联系管理员重置密码',
    icon: 'none'
  })
}

// 处理登录
function handleLogin() {
  if (!loginForm.value.username || !loginForm.value.password) {
    uni.showToast({
      title: '请输入手机号和密码',
      icon: 'none'
    })
    return
  }

  // 调用登录接口
  userApi.login(loginForm.value).then(async res => {
    // 登录成功，保存token
    const token = res.data
    uni.setStorageSync('token', token)
    
    // 获取用户信息
    try {
      const userRes = await userApi.getUserInfo(token)
      if (userRes.code === 200) {
        // 保存用户信息到本地存储
        uni.setStorageSync('userInfo', userRes.data)
        console.log('保存的用户信息：', userRes.data)  // 添加日志
        
        // 显示登录成功
        uni.showModal({
          title: '登录成功',
          content: `Token: ${token}`,
          showCancel: false,
          success: () => {
            // 关闭登录弹窗
            showLoginModal.value = false
            // 设置登录状态
            isLoggedIn.value = true
            // 获取用户积分
            fetchUserScore()
          }
        })
      } else {
        throw new Error(userRes.msg || '获取用户信息失败')
      }
    } catch (err) {
      console.error('获取用户信息失败：', err)
      uni.showToast({
        title: err.message || '获取用户信息失败',
        icon: 'none',
        duration: 2000
      })
      // 清除token，防止状态不一致
      uni.removeStorageSync('token')
      return
    }
  }).catch(err => {
    // 显示后端返回的错误信息
    uni.showToast({
      title: err.msg || '登录失败',
      icon: 'none'
    })
  })
}

// 打开登录弹窗
const openLoginModal = () => {
  showLoginModal.value = true
  // 重置表单
  loginForm.value = {
    username: '',
    password: ''
  }
}

// 页面跳转方法
const navigateTo = (url) => {
  // 检查是否是tabBar页面
  if (url.includes('/src/pages/member/index')) {
    uni.switchTab({
      url: url
    })
  } else {
    uni.navigateTo({
      url: url
    })
  }
}

const takeoutCode = () => {
  const orderInfo = {
    mode: 'takeout',
    board: null
  }
  uni.setStorageSync('orderInfo', JSON.stringify(orderInfo))
  navigateTo('/src/pages/member/index')
}

// 扫码点餐
const scanCode = () => {
  uni.scanCode({
    success: (res) => {
      // 显示扫码结果
      uni.showModal({
        title: '扫码结果',
        content: res.result,
        showCancel: false,
        success: async () => {
          // TODO: 这里可以根据扫码结果进行页面跳转
          // 例如：跳转到点餐页面并传递数据
          console.log('扫码结果：', res.result)
          const board = await boardApi.getBoardById(res.result)
          const orderInfo = {
            mode: 'scan',
            board: board.data
          }
          uni.setStorageSync('orderInfo', JSON.stringify(orderInfo))
          navigateTo('/src/pages/member/index')
        }
      })
    },
    fail: (err) => {
      console.error('扫码失败：', err)
      uni.showToast({
        title: '扫码失败',
        icon: 'none'
      })
    }
  })
}

</script>

<style lang="scss" scoped>
page {
  height: 100%;
  overflow: hidden;
}

.home-page {
  height: 100vh;
  overflow: hidden;
  background: #f8f9fa;

  /* 添加全屏遮罩 */
  &::before {
    content: '';
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 9998;
    display: none;
  }

  &.locked {
    &::before {
      display: block;
    }
  }

  .banner-area {
    width: 100%;
    height: 520rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #eaeaea;
    
    .banner-swiper {
      width: 90%;
      height: 440rpx;
      border-radius: 24rpx;
      overflow: hidden;
    }
    
    .banner-img {
      width: 100%;
      height: 100%;
      border-radius: 24rpx;
      object-fit: cover;
    }
  }

  .score-card {
    margin-top: 50rpx;
    margin-left: 24rpx; // 左边距
    margin-right: 24rpx; // 右边距
    background: #fff;
    border-radius: 24rpx;
    display: flex;
    align-items: center;
    padding: 48rpx 24rpx; // 增加垂直内边距
    box-shadow: 0 4rpx 24rpx rgba(0,0,0,0.03);

    .avatar {
      width: 88rpx;
      height: 88rpx;
      border-radius: 50%;
      margin-right: 24rpx;
    }
    .score-info {
      flex: 1;
      .score-main {
        display: flex;
        align-items: baseline;
        .score-label {
          font-size: 28rpx;
          color: #333;
          margin-right: 12rpx;
        }
        .score-value {
          font-size: 36rpx;
          color: #06C05F;
          font-weight: bold;
        }
      }
      .score-desc {
        font-size: 22rpx;
        color: #999;
        margin-top: 8rpx;
      }
    }
    .member-code {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-left: 24rpx;
      .icon-code {
        width: 48rpx;
        height: 48rpx;
        margin-bottom: 4rpx;
      }
      .code-label {
        font-size: 22rpx;
        color: #666;
      }
    }
  }

  .main-functions {
    margin: 32rpx 24rpx 0 24rpx;
    .func-row {
      display: flex;
      justify-content: space-between;
      margin-bottom: 24rpx;
      .func-item {
        flex: 1;
        background: #fff;
        border-radius: 24rpx;
        margin: 0 8rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 48rpx 0;
        box-shadow: 0 4rpx 24rpx rgba(0,0,0,0.03);

        .func-icon {
          width: 96rpx;
          height: 96rpx;
          margin-bottom: 16rpx;
          
          &.small-icon {
            width: 60rpx;
            height: 60rpx;
          }
        }
        .func-title {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
        }
      }
    }
    .func-row:last-child {
      margin-bottom: 0;
      .func-item {
        padding: 32rpx 0 24rpx 0;
      }
    }
  }

  .login-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }

  .login-content {
    width: 80%;
    max-width: 300px;
    background: #fff;
    border-radius: 12px;
    padding: 20px;
  }

  .login-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
  }

  .login-title {
    font-size: 18px;
    font-weight: bold;
  }

  .close-btn {
    font-size: 24px;
    color: #999;
    cursor: pointer;
  }

  .login-form {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }

  .login-input {
    width: 100%;
    height: 40px;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 0 12px;
    font-size: 14px;
    box-sizing: border-box;
  }

  .forgot-password {
    text-align: right;
    font-size: 14px;
    color: #008CB5;
    margin-top: -5px;
    cursor: pointer;
  }

  .login-btn {
    width: 100%;
    height: 40px;
    background: #008CB5;
    color: #fff;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    margin-top: 10px;
  }
}

</style> 